package com.jie.demo.mockmvc;

import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultHandlers;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;

import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

/**
 * 集成Web环境方式
 * 通过配置文件，启动容器
 */
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest
public class SpringMockMvcInit02 {
    @Autowired
    private WebApplicationContext wac;
    private MockMvc mockMvc;
    @Before
    public void setUp() {
        mockMvc = MockMvcBuilders.webAppContextSetup(wac).build();
    }

    /**
     * 从名字可以看出，RequestBuilder用来构建请求的，其提供了一个方法
     * buildRequest(ServletContext servletContext)用于构建MockHttpServletRequest；
     * 其主要有两个子类MockHttpServletRequestBuilder和MockMultipartHttpServletRequestBuilder（如文件上传使用），即用来Mock客户端请求需要的所有数据。
     * @throws Exception
     */
    @Test
    public void test() throws Exception {
        String content="22";
        MvcResult result =mockMvc.perform(MockMvcRequestBuilders.post("/test2/query").
                accept(MediaType.APPLICATION_JSON_UTF8).content(content))
                .andExpect(status().isOk())
                .andDo(MockMvcResultHandlers.print())
                .andReturn();
        Assert.assertNotNull(result.getResponse().getContentAsString());
        Assert.assertEquals("success",result.getResponse().getContentAsString());
    }
}
